<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="68px"
    >
      <el-form-item label="产品名称" prop="id">
        <el-select
          v-model="queryParams.id"
          clearable
          remote
          :filter-method="hospitalFilter"
          filterable
          placeholder="请选择产品名称"
          class="!w-240px"
        >
          <el-option
            v-for="item in supplierList"
            :key="item.id"
            :label="item.fullName"
            :value="item.id"
          />
          <!-- 添加加载更多按钮 -->
          <div class="text-center py-2" v-if="hasMore">
            <el-button size="small" @click="loadMore">加载更多</el-button>
          </div>
        </el-select>
      </el-form-item>
      <!-- <el-form-item label="产品名称" prop="productName">
        <el-input
          v-model="queryParams.productName"
          placeholder="请输入产品名称"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="产品条码" prop="barCode">
        <el-input
          v-model="queryParams.barCode"
          placeholder="请输入产品条码"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="产品分类编号" prop="categoryId">
        <el-input
          v-model="queryParams.categoryId"
          placeholder="请输入产品分类编号"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="单位编号" prop="unitId">
        <el-input
          v-model="queryParams.unitId"
          placeholder="请输入单位编号"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="产品规格" prop="standard">
        <el-input
          v-model="queryParams.standard"
          placeholder="请输入产品规格"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="科室编号" prop="deptId">
        <el-input
          v-model="queryParams.deptId"
          placeholder="请输入科室编号"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="带量数量" prop="count">
        <el-input
          v-model="queryParams.count"
          placeholder="请输入带量数量"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="创建时间" prop="createTime">
        <el-date-picker
          v-model="queryParams.createTime"
          value-format="YYYY-MM-DD HH:mm:ss"
          type="daterange"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
          class="!w-220px"
        />
      </el-form-item> -->
      <el-form-item>
        <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button>
        <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table v-loading="loading" :data="list" :stripe="true" :show-overflow-tooltip="true">
      <el-table-column label="条码" align="center" prop="barCode" />
      <el-table-column label="名称" align="center" prop="name" width="200%"/>
      <el-table-column label="规格" align="center" prop="standard" width="100px"/>
      <el-table-column label="分类" align="center" prop="categoryName" width="80px"/>
      <el-table-column label="单位" align="center" prop="unitName" />
      <el-table-column label="带量总数" align="center" prop="quantityCount" />
      <el-table-column label="剩余带量数" align="center" prop="allocationStatus" width="100%"/>
     
      <!-- <el-table-column
        label="有效期"
        align="center"
        prop="validityDate"
        :formatter="dateFormatter2"
        width="120px"
      />
      <el-table-column label="批次" align="center" prop="batch"  width="120px"/> -->
      <el-table-column
        label="采购价格"
        align="center"
        prop="purchasePrice"
        :formatter="erpPriceTableColumnFormatter"
         width="100px"
      />
      <!-- <el-table-column
        label="销售价格"
        align="center"
        prop="salePrice"
        :formatter="erpPriceTableColumnFormatter"
         width="100px"
      />
      <el-table-column
        label="最低价格"
        align="center"
        prop="minPrice"
        :formatter="erpPriceTableColumnFormatter"
        width="100px"
      /> -->
      <el-table-column label="状态" align="center" prop="status"  width="100px">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.COMMON_STATUS" :value="scope.row.status" />
        </template>
      </el-table-column>

      <el-table-column label="是否带量" align="center" prop="isQuantity"  width="80px">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.ERP_IS_QUANTITY" :value="scope.row.isQuantity" />
        </template>
      </el-table-column>

      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        :formatter="dateFormatter"
        width="180px"
      />
      <el-table-column label="操作" align="center" width="110">
        <template #default="scope">
          <el-button
            link
            type="primary"
            @click="openForm('update', scope.row.id)"
            v-hasPermi="['spd:product:update']"
          >
            分配
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <DepartQuantityForm ref="formRef" @success="getList" />
</template>

<script setup lang="ts">
import debounce from 'lodash/debounce'
import { dateFormatter } from '@/utils/formatTime'
import download from '@/utils/download'
import { DepartQuantityApi, DepartQuantityVO } from '@/api/spd/manager/departquantity'
import { ProductApi, ProductVO } from '@/api/spd/product/product'
import { ProductCategoryApi, ProductCategoryVO } from '@/api/erp/product/category'
import { ProductUnitApi, ProductUnitVO } from '@/api/erp/product/unit'
import DepartQuantityForm from './DepartQuantityForm.vue'
import { DICT_TYPE } from '@/utils/dict'
import { defaultProps, handleTree } from '@/utils/tree'
import { erpPriceTableColumnFormatter } from '@/utils'

/** 带量分配 列表 */
defineOptions({ name: 'DepartQuantity' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化
const loading = ref(true) // 列表的加载中
const list = ref<ProductVO[]>([]) // 列表的数据
const supplierList = ref<ProductVO[]>([])  // 供应商列表
const total = ref(0) // 列表的总页数
const currentPage = ref(1) // 当前页码
const pageSize = ref(40) // 每页数据量
const totalPages = ref(0) // 总页数
const jrvalue= ref('')
// 添加加载状态
const isLoadingMore = ref(false)
// 添加是否有更多数据的标识
const hasMore = ref(true)
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  productId: undefined,
  productName: undefined,
  barCode: undefined,
  categoryId: undefined,
  name:undefined,
  id:undefined,
  fullName:undefined,
  unitId: undefined,
  standard: undefined,
  deptId: undefined,
  allocationStatus:undefined,
  count: undefined,
  createTime: [],
  isQuantity:1,
  quantityCount:undefined
})
const queryFormRef = ref() // 搜索的表单
const categoryList = ref<ProductCategoryVO[]>([]) // 产品分类列表
const unitList = ref<ProductUnitVO[]>([])//单位列表
/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await ProductApi.selectPages(queryParams)
    list.value = data.list
    total.value = data.total
  } catch (error) {
    console.error('selectPages调用失败:', error);
  } finally {
    loading.value = false
  }
}
/**
 * 键入监听方法
 */
 const hospitalFilter =(params)=> {
  //判断键入是否有值
  if(params!==""){
    //有值调用防抖方法
    debouncedSearch(params)
    jrvalue.value = params
  }else{
    //没有键入值，集合为空
    supplierList.value=[]
    jrvalue.value = ''
    currentPage.value = 1
  }
}
/**
 * 根据键入的值查询产品列表
 */
 const productLists = async (params) => {
  isLoadingMore.value = true
  try {
    // 加载产品列表
    const supplierData = await ProductApi.getProductToget(params, currentPage.value, pageSize.value)
    if (currentPage.value === 1) {
      // 第一页数据直接替换
      supplierList.value = handleTree(supplierData.list, 'id')
    } else {
      // 非第一页数据追加到现有列表
      supplierList.value = [
        ...supplierList.value,
        ...handleTree(supplierData.list, 'id')
      ]
    }
    
    // 更新总页数
    totalPages.value = Math.ceil(supplierData.total / pageSize.value)
    // 判断是否还有更多数据
    hasMore.value = currentPage.value < totalPages.value
  } catch (error) {
    console.error('加载更多数据失败:', error)
  } finally {
    isLoadingMore.value = false
  }
}

/** 加载更多数据 */
const loadMore = () => {
  if (isLoadingMore.value || !hasMore.value) return
  currentPage.value++
  productLists(jrvalue.value)
}

 // 创建一个防抖函数来处理搜索操作
 const debouncedSearch =debounce((params,delay = 500) => { 
      //定义等待时间
      const timer = ref() 
      // 模拟异步数据获取（例如API调用）
      if(timer.value){
          //清除等待时间
          clearTimeout(timer.value); 
        }
      //等待时间赋值
      timer.value = setTimeout(async() => {
        //调用后端根据键入的值查询产品列表方法
        productLists(params)
      }, delay); // 延迟500毫秒以模拟网络延迟或数据处理时间
  }, 500); // 防抖等待时间为500毫秒   


/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  hasMore.value = true
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  currentPage.value=1
  handleQuery()
}


/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await DepartQuantityApi.deleteDepartQuantity(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

/** 初始化 **/
onMounted(async() => {
  getList()
})


</script>